// 筛选组件
import React from 'react';
import { Drawer, Input, Button, Tag, message } from 'antd';
import { request } from '@/utils/request';
import { useI18n } from '@/utils/in18';

type FilterValues = {
    keyword?: string;
    race?: string; // person | other（单选）
    category?: string; // real_male | real_female | anime_male | anime_female（单选）
    origin?: string[]; // tag key（可多选）
};

interface FilterSheetProps {
    open: boolean;
    onClose: () => void;
    onConfirm: (values: FilterValues) => void;
    onReset: () => void;
}

// 稳定的出处标签 key 列表（label 走 i18n）
const ORIGIN_KEYS = [
    'naruto',
    'one_piece',
    'bleach',
    'aot',
    'genshin',
    'fgo',
    'vocaloid',
    'eva',
    'konosuba',
    'demon_slayer',
    'jjk',
    'bnha',
    'overlord',
    're_zero',
    'spyxfamily',
    'sao',
    'idol',
    'vtuber',
    'original',
    'others',
];

const { CheckableTag } = Tag as any;

const FilterSheet: React.FC<FilterSheetProps> = ({ open, onClose, onConfirm, onReset }) => {
    const { locale, t } = useI18n();
    const [keyword, setKeyword] = React.useState<string>('');
    const [selectedRace, setSelectedRace] = React.useState<string | null>(null);
    const [selectedCategory, setSelectedCategory] = React.useState<string | null>(null);
    // origin 支持多选
    const [selectedOrigins, setSelectedOrigins] = React.useState<string[]>([]);
    const [visibleCount, setVisibleCount] = React.useState<number>(10);

    // 关闭时重置可视数量，保持一致体验
    React.useEffect(() => {
        if (!open) setVisibleCount(10);
    }, [open]);

    const originTags = React.useMemo(() => ORIGIN_KEYS.map(key => ({ key, label: t(`FilterSheet.origin_tags.${key}`) })), [locale, t]);
    const visibleTags = React.useMemo(() => originTags.slice(0, visibleCount), [originTags, visibleCount]);

    // 单选切换：如果重复点击同一项则取消选择
    const toggleSingle = (setter: React.Dispatch<React.SetStateAction<string | null>>, value: string) => {
        setter(prev => (prev === value ? null : value));
    };

    // 选择 race 后立即应用并关闭弹窗
    const handleSelectRace = (value: string) => {
        const newVal = selectedRace === value ? null : value;
        setSelectedRace(newVal);
        // 立即派发搜索/确认，保证父组件按新条件刷新
        try {
            onConfirm({
                keyword: keyword.trim() || undefined,
                race: newVal || undefined,
                category: selectedCategory || undefined,
                origin: selectedOrigins.length ? selectedOrigins : undefined,
            });
        } catch (e) { }
        // 关闭弹窗
        try { onClose(); } catch (e) { }
    };

    // 选择 category 后立即应用并关闭弹窗
    const handleSelectCategory = (value: string) => {
        const newVal = selectedCategory === value ? null : value;
        setSelectedCategory(newVal);
        try {
            onConfirm({
                keyword: keyword.trim() || undefined,
                race: selectedRace || undefined,
                category: newVal || undefined,
                origin: selectedOrigins.length ? selectedOrigins : undefined,
            });
        } catch (e) { }
        try { onClose(); } catch (e) { }
    };

    // 多选切换：用于 origin 标签的多选逻辑
    const toggleMultiOrigin = (value: string) => {
        setSelectedOrigins(prev => (prev.includes(value) ? prev.filter(v => v !== value) : [...prev, value]));
    };

    const handleReset = () => {
        // 重置所有选择为初始状态
        setKeyword('');
        setSelectedRace(null);
        setSelectedCategory(null);
        setSelectedOrigins([]);
        setVisibleCount(10);
        onReset();
    };

    const handleConfirm = () => {
        onConfirm({
            keyword: keyword.trim() || undefined,
            race: selectedRace || undefined,
            category: selectedCategory || undefined,
            origin: selectedOrigins.length ? selectedOrigins : undefined,
        });
    };

    // 当用户在搜索框输入内容并点击搜索时，按照指定的参数向后端发起请求
    const handleSearch = async (val: string) => {
        const q = String(val ?? keyword ?? '').trim();
        if (!q) {
            message.warning(t('FilterSheet.search_empty'));
            return;
        }
        try {
            const payload = {
                search: q,
                category: '',
                race: '',
                origin: '',
                name: '',
                sort: 'likes',
                page: 1,
                page_size: 4,
                language: 'ey',
                information: ['image_url', 'name'],
            } as any;
            const res = await request.post('/api/template/getTemplatesRoute', payload);
            if (res && res.data && res.data.success === true) {
                const data = res.data.data || [];
                if (!Array.isArray(data) || data.length === 0) {
                    message.warning(t('FilterSheet.search_no_results'));
                    // 不派发事件，保持现有数据不变
                } else {
                    // 若需要，派发全局事件通知其他页面（例如首页）可以选择监听并处理搜索结果
                    try { window.dispatchEvent(new CustomEvent('home_search_results', { detail: { results: data, search: q } } as any)); } catch (e) { }
                }
            } else {
                message.warning((res && res.data && res.data.msg) ? res.data.msg : t('FilterSheet.request_failed'));
            }
        } catch (e) {
            message.warning(t('FilterSheet.request_error'));
        }
    };

    return (
        <Drawer
            placement="bottom"
            height={'80vh'}
            open={open}
            onClose={onClose}
            closeIcon={false}
            styles={{
                body: { padding: 0, background: 'transparent' },
                header: { display: 'none' },
                content: { background: 'transparent' },
            }}
        >
            {/* 背景和容器：适配明暗主题 */}
            <div className="h-full w-full bg-white dark:bg-[#0b0b0b] text-black dark:text-white rounded-t-2xl overflow-hidden">
                {/* 顶部拖拽条视觉 */}
                <div className="w-full flex justify-center py-2">
                    <div className="w-12 h-1.5 rounded-full bg-gray-300 dark:bg-gray-700" />
                </div>

                {/* 搜索栏：提示可检索角色名字和番名 */}
                <div className="px-4 pb-3">
                    <Input.Search
                        allowClear
                        value={keyword}
                        onChange={(e) => setKeyword(e.target.value)}
                        placeholder={t('FilterSheet.search_placeholder')}
                        className="[&_.ant-input]:bg-white dark:[&_.ant-input]:bg-[#141414] dark:[&_.ant-input]:text-white"
                    />
                </div>

                <div className="px-4 pb-24 overflow-y-auto" style={{ height: 'calc(80vh - 96px)' }}>
                    {/* 种族：人类 / 其他 -> person / other */}
                    {/* <div className="mb-4">
                        <div className="text-sm text-gray-600 dark:text-gray-400 mb-2">{t('FilterSheet.species_label')}</div>
                        <div className="flex flex-wrap gap-2">
                            {[
                                { key: 'person', label: t('FilterSheet.race_person') },
                                { key: 'other', label: t('FilterSheet.race_other') },
                            ].map(item => (
                                <Button
                                    key={item.key}
                                    size="small"
                                    type={selectedRace === item.key ? 'primary' : 'default'}
                                    onClick={() => handleSelectRace(item.key)}
                                >
                                    {item.label}
                                </Button>
                            ))}
                        </div>
                    </div> */}

                    {/* 性别：真人男、真人女、动漫男、动漫女 -> real_male | real_female | anime_male | anime_female */}
                    <div className="mb-4">
                        <div className="text-sm text-gray-600 dark:text-gray-400 mb-2">{t('FilterSheet.gender_label')}</div>
                        <div className="flex flex-wrap gap-2">
                            {[
                                { key: 'anime_female', label: t('FilterSheet.gender_anime_female') },
                                { key: 'real_female', label: t('FilterSheet.gender_real_female') },
                                { key: 'anime_male', label: t('FilterSheet.gender_anime_male') },
                                { key: 'real_male', label: t('FilterSheet.gender_real_male') },
                            ].map(item => (
                                <Button
                                    key={item.key}
                                    size="small"
                                    type={selectedCategory === item.key ? 'primary' : 'default'}
                                    onClick={() => handleSelectCategory(item.key)}
                                >
                                    {item.label}
                                </Button>
                            ))}
                        </div>
                    </div>

                    {/* 出处：标签，默认展示 10 个，每次展开 +10 */}
                    {/* <div className="mb-4">
                        <div className="text-sm text-gray-600 dark:text-gray-400 mb-2">{t('FilterSheet.origin_label')}</div>
                        <div className="flex flex-wrap gap-2">
                            {visibleTags.map(tag => {
                                const isChecked = selectedOrigins.includes(tag.key);
                                return (
                                    <CheckableTag
                                        key={tag.key}
                                        checked={isChecked}
                                        onChange={() => toggleMultiOrigin(tag.key)}
                                        className={`px-2 py-1 rounded select-none transition-colors duration-150 ${isChecked ? 'bg-blue-500 dark:bg-blue-600 text-white' : 'bg-gray-100 dark:bg-[#141414] text-gray-800 dark:text-gray-300'}`}
                                    >
                                        {tag.label}
                                    </CheckableTag>
                                );
                            })}
                        </div>
                        {visibleCount < originTags.length && (
                            <div className="mt-2">
                                <Button size="small" onClick={() => setVisibleCount(c => Math.min(c + 10, originTags.length))}>{t('FilterSheet.expand_more')}</Button>
                            </div>
                        )}
                    </div> */}
                </div>

                {/* 底部操作栏：重置 / 确认 */}
                <div className="absolute bottom-0 left-0 right-0 border-t border-gray-200 dark:border-gray-800 bg-white dark:bg-[#0b0b0b] px-4 py-3 flex items-center justify-end">
                    <Button className='mr-2' onClick={handleReset}>{t('FilterSheet.reset')}</Button>
                    <Button type="primary" onClick={handleConfirm}>{t('FilterSheet.confirm')}</Button>
                </div>
            </div>
        </Drawer>
    );
};

export default FilterSheet;


